package com.familyigo.gdemo;

import org.jdbi.v3.core.Jdbi;
import org.jdbi.v3.core.h2.H2DatabasePlugin;
import org.jdbi.v3.sqlobject.SqlObjectPlugin;
import org.jdbi.v3.stringtemplate4.StringTemplateEngine;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Hello world!
 */
public class App {
    public static void main(String[] args) {
        // 创建 JDBI 实例，连接到 H2 内存数据库
        Jdbi jdbi = Jdbi.create("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", "sa", "");
        jdbi.installPlugin(new SqlObjectPlugin());
        //jdbi
        jdbi.setTemplateEngine(new JexlAwareStringTemplateEngine());
        jdbi.setSqlLogger(new MySqlLogger());
        jdbi.addCustomizer(new DefineMapStatementCustomizer());
        // 使用 JDBI 打开一个句柄
        jdbi.useExtension(UserDao.class, dao -> {
            // 创建 users 表
            dao.createTable();

            // 插入示例数据
            dao.insert("Alice", 25, "Active");
            dao.insert("Bob", 30, "Inactive");

            // 查询所有用户数据
            if (false) {
                List<User> users = dao.listUsers(new User());

                // 打印查询结果
                for (User user : users) {
                    System.out.println(user);
                }
            }
            DefineMap defineMap = DefineMap.build("defineName", true);


            User user = new User();
            user.setName("Bob");
            System.out.println("开始我的测试 ~~");


            List<Map<String, Object>> maps = jdbi.withHandle(h ->
                    h.createQuery("SELECT * FROM users <if(defineKey)>WHERE name = :name <endif>")
                            .define("defineKey", true)
                            .bind("bindName", "bindValue")
                            .bindMap(defineMap)
                            .bind(0, "bindValue0")
                            .bindBean(user).mapToMap()
                            .list()
            );
            maps.forEach(System.out::println);

            List<User> users = dao.listUsers(user);
            users.forEach(System.out::println);

        });
    }
}
